<template>
	<div class="manage">
		<!-- 添加或修改对话框 -->
		<el-dialog :title="operateType === 'add' ? '新增角色' : '更新角色'" :visible.sync="isShow" width="600px" append-to-body>
		   <el-form :model="operateForm" :rules="rules" ref="form" label-width="90px">
		      <el-row>
		         <el-col :span="24">
					 <el-form-item v-if="operateForm.roleId == undefined" label="角色名称" prop="roleName">
					    <el-input v-model="operateForm.roleName" placeholder="请输入角色名称" maxlength="30" />
					 </el-form-item>
		         </el-col>
		      </el-row>
		      <el-row>
		         <el-col :span="24">
		            <el-form-item label="权限字符" prop="roleKey">
		               <el-input v-model="operateForm.roleKey" placeholder="请输入权限字符" maxlength="30" />
		            </el-form-item>
		         </el-col>
		      </el-row>			
				<el-row>
					<el-col :span="24">
						<el-form-item label="菜单权限">
						  <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
						  <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
						  <el-tree
							class="tree-border"
							:data="menuOptions"
							show-checkbox
							ref="menu"
							node-key="id"
							empty-text="加载中，请稍候"
							:check-strictly="!menuParentSon"
							:default-expand-all="menuExpand"
							:props="defaultProps"
						  ></el-tree>
						</el-form-item>
					</el-col>
				</el-row>
		      <el-row>
				 <el-col :span="24">
				    <el-form-item label="备注">
				       <el-input v-model="operateForm.remark" type="textarea" placeholder="请输入内容"></el-input>
				    </el-form-item>
				 </el-col>
		      </el-row>		
		   </el-form>
		   <template #footer>
		      <div class="dialog-footer">
		         <el-button type="primary" @click="confirm">确 定</el-button>
		         <el-button @click="isShow = false">取 消</el-button>
		      </div>
		   </template>
		</el-dialog>
		
		<div class="manage-header">
			<el-form style="width: 100%;" label-width="100px" :model="searchForm" ref="sform" inline>
				<el-button type="primary" @click="addHandler">+ 新增</el-button>
				<div style="float: right;">
					<el-form-item label="查询关键字">
						<el-input  v-model="searchForm.roleName" placeholder="查询关键字" clearable></el-input>
					</el-form-item>
					<el-button  type="primary" @click="getList(searchForm.roleName)">搜索</el-button>
				</div>
			</el-form>
		</div>
		<common-table :tableData="tableData" :tableLabel="tableLabel" :config="config" 
		@changePage="getList()" @edit="editHandler" @del="delHandler"></common-table>
	</div>
</template>

<script>
import CommonForm from '/src/components/CommonForm.vue'
import CommonTable from '/src/components/CommonTable.vue'
import { getRoleList,addRole,updateRole,delRole } from '/api/roleapi.js'
import { getMenuTree } from '/api/menuapi.js'
export default {
	name: 'role',
	components:{
		CommonForm,
		CommonTable
	},
	data(){
		return {
			operateType: 'add',
			isShow: false,
			operateForm:{
				roleName: '',
				roleKey: '',
				remark: '',
				menuIds: [],
			},
			formLabel:[
				{
					model: 'roleName',
					label: '角色名称',
					type: 'input'
				}
			],
			searchForm:{
				roleName: ''
			},
			tableData: [],
			tableLabel: [
				{
					prop: "roleName",
					label: "角色名称",
					width: "30%",
				},
				{
					prop: "roleKey",
					label: "角色代码",
					width: "30%",
				},
				{
					prop: "remark",
					label: "备注",
					width: "40%",
				}
			],
			config: {
				page: 1,
				size: 10,
				total: 30
			},
			// 表单校验
			rules: {
			  roleName: [
			    { required: true, message: "角色名称不能为空", trigger: "blur" },
			    { min: 2, max: 20, message: '角色名称长度必须介于 2 和 20 之间', trigger: 'blur' }
			  ],
			  roleKey: [
			    { required: true, message: "角色代码不能为空", trigger: "blur" },
			  ],
			},
			menuExpand: false,
			menuParentSon: true,
			menuNodeAll: false,
			menuOptions: [],
			defaultProps: {
			  children: "children",
			  label: "label"
			}
		}
	},
	methods:{
	//将数据库表格数据转换为树形结构数据
	menuTreeData(list){
		function getChildMenu(item){
			let submenu = menu.filter(s=>{
				if(s.pid != item.id) return false
				return true
			})
			if(submenu.length>0){
				submenu.forEach(t=>{
					getChildMenu(t)
				})
				item.children = submenu
			}
		}
		let menu = []
		let menuList = []
		list.forEach(t=>{
			if(t.menuName != '首页'){
				let item = {
					id: t.menuId,
					pid: t.parentId,
					name: t.component,
					label: t.menuName,
					path: t.component,
					url: t.path,
					icon: t.icon
				}
				menu.push(item)
			}
		})
		menu.forEach(t=>{
			if(t.pid == 0){
				getChildMenu(t)
				menuList.push(t)
			}
		})
		return menuList
	},
    // 全选
    selectAllNodes: function() { //递归函数
      //  获取根节点
      let rootNode = this.$refs.menu.getNode(this.menuOptions[0].id).parent;
      travelNodes(rootNode);
      function travelNodes(tmpRoot) {
        // 选中该节点
        tmpRoot.checked = true;
        // 叶子节点
        if (tmpRoot.childNodes.length === 0) {
          return;
        }
        // 不是叶子节点,递归遍历
        else {
          let tmpChildNoes = tmpRoot.childNodes;
          for (let i = 0; i < tmpChildNoes.length; i++) {
            travelNodes(tmpChildNoes[i]);
          }
        }
      }
    },
	
	// 清空
	clearAllNodes: function() {
	  this.$refs.menu.setCheckedKeys([]);
	},
	    
    // 全部展开/折叠
    expandedAllNodes(val) { 
      //  获取根节点
      let rootNode = this.$refs.menu.getNode(this.menuOptions[0].id).parent;
      travelNodes(rootNode);
      function travelNodes(tmpRoot) {
        // 选中该节点
        tmpRoot.expanded = val;
        // 叶子节点
        if (tmpRoot.childNodes.length === 0) {
          return;
        }
        // 不是叶子节点,递归遍历
        else {
          let tmpChildNoes = tmpRoot.childNodes;
          for (let i = 0; i < tmpChildNoes.length; i++) {
            travelNodes(tmpChildNoes[i]);
          }
        }
      }
    },
		
		handleCheckedTreeExpand(value){
			this.expandedAllNodes(value);
		},
		
		handleCheckedTreeNodeAll(value){
			if(value){
			  this.selectAllNodes()
			}else {
			  this.clearAllNodes()
			}
		},

		confirm(){
			this.$refs["form"].validate(valid=>{
				if (valid){
					this.operateForm.menuIds = this.$refs.menu.getCheckedKeys()
					if(this.operateType === 'edit'){
						updateRole(this.operateForm).then(res => {
							// console.log(res,'updateRole')
							this.isShow=false
							this.getList()
						})
					}
					else{
						addRole(this.operateForm).then(res => {
							// console.log(res,'addRole')
							this.isShow=false
							this.getList()
						})
					}
				}
			})

		},
		getList(roleName = ''){
			this.config.loading = true
			roleName ? (this.config.page = 1) : ''
			getRoleList({
				pageNum: this.config.page,
				pageSize: this.config.size,
				roleName
			}).then( res =>{
				let data = res.data
				this.tableData = data.rows
				// console.log(data.rows,'role and menuids')
				this.config.total = data.total
				this.config.loading = false
			})
		},
		syncSelectMenu(){
			setTimeout(() => {
				this.$refs.menu.setCheckedKeys( this.operateForm.rolemenu )
			}, 50);
		},
		addHandler(){
			this.isShow = true
			this.operateType = 'add'
			this.operateForm = {
				roleName: '',
				roleKey: '',
				remark: '',
				rolemenu: []
			}
			this.syncSelectMenu()
		},
		editHandler(row){
			this.operateType = 'edit'
			this.isShow = true
			this.operateForm = row
			this.operateForm.rolemenu = row.menuIds
			this.syncSelectMenu()
		},
		delHandler(row){
			this.$confirm("此操作将永久删除该角色，是否继续？", "提示",{
				confirmButtonText: "确认",
				cancelButtonText: "取消",
				type: "warning"
			}).then(()=>{
				const id = row.roleId
				delRole(id).then(() => {
					this.$message({
						type: 'success',
						message: '删除成功'
					})
					this.getList()
				})
			})
		}
	},
	created(){
		this.getList()
		getMenuTree().then(res =>{
			// console.log(res.data.data,'转换之前')
			this.menuOptions = this.menuTreeData(res.data.data)
			// console.log(this.menuOptions,'转换之后')
		})
	}
}
</script>

<style>
	.manage-header{
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
</style>
